package java_thinking.unit_17._17_9_10;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Desc:   生成不同的hashCode案例
 * @author: cww
 * @DateTime: 2019-04-20 15:45
 */

public class CountedString {
    private static List<String> created = new ArrayList<>();
    private String s;
    private int id = 0;

    public CountedString(String str) {
        s = str;
        created.add(s);
        //id是用来统计同一个string在CountedString里用的次数
        for (String s2 : created) {
            if (s2.equals(s)) id++;
        }
    }

    @Override
    public String toString() {
        return "String: " + s + " id: " + id + " hashCode(): " +hashCode();
    }

    /**
     * hashCode和equals都基于CountedString的这两个域来生成结果，所以，即使内容一样，但是id也会不一样，
     * 所以可能使得散列码并不相同
     * @return
     */
    @Override
    public int hashCode() {
        int result = 17;
        result = 37 * result + s.hashCode();
        result = 37 * result + id;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        return obj instanceof CountedString && s.equals(((CountedString)obj).s)
                && id == ((CountedString)obj).id;
    }

    public static void main(String[] args) {
        Map<CountedString,Integer> map = new HashMap<>();
        CountedString[] cs = new CountedString[5];
        for (int i = 0; i < cs.length; i++) {
            cs[i] = new CountedString("hi");
            map.put(cs[i],i);
        }
        System.out.println(map);
        for (CountedString cdString : cs) {
            System.out.println("Looking up " + cdString);
            System.out.println(map.get(cdString));
        }
    }
}
